package com.tofch.biproject.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * excel 相关工具类
 */
@Slf4j
public class ExcelUtils {


    public static String excelToCsv(MultipartFile multipartFile)  {


//        File file = null;
//        try {
//            file = ResourceUtils.getFile("classpath:网站数据.xlsx");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        /**
         * 接收上传的大件信息
         */
        List<Map<Integer, String>> list = null;
        log.info("{}",multipartFile);
        /**
         * 调用exsyexcel读取信息
         */
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("表格处理错误");
        }

        if(CollectionUtils.isEmpty(list)){
            return "";
        }

        //转换CSv
        //读取表头
        /**
         * 数据压缩
         * 使用stearm 筛除空的数据
         * 并使用stringBuilder组装成字符串，用，分割
         *
         */
        StringBuilder stringBuilder = new StringBuilder();

        LinkedHashMap<Integer,String> headMap = (LinkedHashMap)list.get(0);

        List<String> headerList = headMap.values().stream().filter(header -> ObjectUtils.isNotEmpty(header)).collect(Collectors.toList());

        stringBuilder.append(StringUtils.join(headerList,',')).append("\n");


        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer,String> dataMap = (LinkedHashMap)list.get(i);


            List<String> dataList = dataMap.values().stream().filter(header -> ObjectUtils.isNotEmpty(header)).collect(Collectors.toList());

            stringBuilder.append(StringUtils.join(dataList,",")).append("\n");

        }



        return stringBuilder.toString();
    }


}
